import React, { Component } from 'react';

class Cart extends Component {
    constructor(props) {
        super(props)
        this.state = {
            username: '小好',
            city: '南京',
            cities: ['北京', '上海', '杭州', '南京']
        }
    }
    // 1.箭头函数 
    // 2.事件对象
    // 3.setState方法修改数据
    changeUserName = (e) => {
        this.setState({
            username: e.target.value
        })
    }
    changeCity = (e) => {
        this.setState({
            city: e.target.value
        }, () => {
            // 由于setState是异步修改后,如果获取state中的数据,那么需要设置回调函数
            console.log(this.state.city);
        })

    }
    render() {
        return (
            <div>
                <p>{this.state.username}</p>
                <p>
                    <label htmlFor="username" ></label>
                    <input type="text" value={this.state.username} id="username" onChange={this.changeUserName} />
                </p>
                <p>
                    <select value={this.state.city} onChange={this.changeCity}>
                        {
                            this.state.cities.map((item, index) => {
                                return (
                                    <option value={item} key={index}>{item}</option>
                                )
                            })
                        }
                    </select>
                </p>
            </div>
        );
    }
}

export default Cart;